//
//  AccountHomeViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/15.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import AlamofireImage
import PKHUD
import Alamofire

private let normalMemberColor = UIColor(fromRGB: 0xCBCBCB)
private let vipMemberColor = UIColor(fromRGB: 0xEDBF64)

class AccountHomeViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var avatarView: UIView!
  @IBOutlet private weak var avatarImageView: UIImageView!
  @IBOutlet private weak var nicknameLabel: UILabel!
  @IBOutlet private weak var memberButton: UIButton!
  @IBOutlet private weak var memberIcon: UIImageView!
  @IBOutlet private weak var vipIcon: UIImageView!
  @IBOutlet private weak var versionLabel: UILabel!
  @IBOutlet private weak var playtimeLabel: UILabel!
  @IBOutlet private weak var codeConsumeButton: UIButton!
  @IBOutlet private weak var checkInButton: UIButton!
  @IBOutlet private weak var checkInStatusButton: UIButton!
    @IBOutlet weak var vipValidTimeLabel: UILabel!
    @IBOutlet weak var vipValidTimeLabelHeight: NSLayoutConstraint!
    @IBOutlet weak var memberButtonHeight: NSLayoutConstraint!
    
  // MARK: - Private vars
  
  
  
  // MARK: - Private methods
  
  private func prepareUI() {
    avatarView.clipsToBounds = true
    avatarView.layer.cornerRadius = 38
    avatarView.backgroundColor = .clear
    avatarView.layer.borderWidth = 2
    
    memberButton.addTarget(self, action: #selector(actionMemberButton(_:)), for: .touchUpInside)
    
    versionLabel.text = "当前版本：\(Config.appEnvironment == .TestFlight ? "内测" : "v")\(Bundle.main.releaseVersionNumber!)(\(Bundle.main.buildVersionNumber!))"
    
    let currentUser = UserManager.shared.currentUser!
    if let avatarURL = currentUser.avatar.getURL(size: .thumb) {

      avatarImageView.af_setImage(withURL: avatarURL)
    }
    nicknameLabel.text = UserManager.shared.currentUser!.nickname
    
    if currentUser.isPremium {  //是会员
      avatarView.layer.borderColor = vipMemberColor.cgColor
      nicknameLabel.textColor = vipMemberColor
      vipIcon.isHidden = false
      memberIcon.image = UIImage(named: "AccountMemberIconGold")
      memberButton.setTitleColor(vipMemberColor, for: .normal)
        vipValidTimeLabel.textColor = vipMemberColor
        vipValidTimeLabelHeight.constant = 14;
        memberButton.setTitle("查看会员", for: .normal)

    } else { //不是会员
      avatarView.layer.borderColor = normalMemberColor.cgColor
      nicknameLabel.textColor = normalMemberColor
      vipIcon.isHidden = true
      memberIcon.image = UIImage(named: "AccountMemberIconGray")
      memberButton.setTitleColor(normalMemberColor, for: .normal)
        vipValidTimeLabelHeight.constant = 0;
        memberButton.setTitle("加入会员", for: .normal)
    }
    
    codeConsumeButton.isHidden = true
    
    //添加用户信息监听
    NotificationCenter.default.addObserver(self, selector: #selector(updateUserInfo), name: .updateUserInfo, object: nil)
    }
    
  private func loadCodeSetting() {
    codeConsumeButton.isHidden = true
    API.shared.requestAPI (
      APIURLStrings.codeSetting,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        if json["enabled"].boolValue {
          self.codeConsumeButton.isHidden = false
        }
    }) { (message, code) in
    }
  }
  
  private func loadPlaytime() {
    API.shared.requestAPI (
      APIURLStrings.getTotalPlaytime,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        if let seconds = json["total_play_time"].int {
          var playtimeMessage = ""
          let hours: Int = seconds / 3600
          let minutes: Int = (seconds % 3600) / 60
          if hours == 0 {
            if minutes == 0 {
              playtimeMessage = "未收听节目"
            } else {
              playtimeMessage = "\(minutes)分钟"
            }
          } else {
            if minutes == 0 {
              playtimeMessage = "\(hours)小时"
            } else {
              playtimeMessage = "\(hours)小时\(minutes)分钟"
            }
          }
          self.playtimeLabel.text = playtimeMessage
        } else {
          self.playtimeLabel.text = "无法获取"
        }
    }) { (message, code) in
      self.playtimeLabel.text = "无法获取"
    }
  }
  
  private func loadCheckInStateOfToday() {
    API.shared.requestAPI (
      APIURLStrings.isCheckedInToday,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        if json["is_checked_in_today"].boolValue == true {
          self.checkInButton.isEnabled = false
          self.checkInButton.setTitle("今日已签到", for: .normal)
        } else {
          self.checkInButton.isEnabled = true
          self.checkInButton.setTitle("签到", for: .normal)
        }
    }) { (message, code) in
      loggingPrint("Checking checkInStateOfToday failed. \(message)")
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prefersLargeTitles = true
    
    
    prepareUI()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    loadPlaytime()
    loadCodeSetting()
    loadCheckInStateOfToday()
    requestVipValidTime()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func logout(_ sender: UIBarButtonItem) {
    let alert = UIAlertController(title: "确定退出登录吗？", message: nil, cancelTitle: "取消", cancelHandler: nil, confirmTitle: "退出登录") { _ in
      
      func logoutLocally() {
        UserManager.shared.currentUser = nil
        NotificationCenter.default.post(name: .currentUserUpdated, object: nil)
        NotificationCenter.default.post(name: .didLogout, object: nil)
        do {
          try IAPPurchasedItem.removeAll()
        } catch { }
      }
      
      API.shared.requestAPI (
        APIURLStrings.logout,
        method: .post,
        header: API.shared.memeberHeader,
        successCallback: { json in
          loggingPrint("Remote logout success.")
          logoutLocally()
      }, errorCallback: { message, code in
        loggingPrint("Remote logout failed. \(message)")
        logoutLocally()
      })
    }
    present(alert, animated: true)
  }
    
    func requestVipValidTime() {

        let urlString = APIURLStrings.getVipValidtime
        let url = URL.init(string: urlString)
        let request = NSMutableURLRequest.init(url: url!)
        request.httpMethod = "POST"
        request.httpBody = "uid=\(UserManager.shared.currentUser!.identifier)".data(using: .utf8)
        let config = URLSessionConfiguration.default;
        let session = URLSession.init(configuration: config)
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            do {
                let dic:[String:Any] = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary
                let status:Int = dic["status"] as! Int
                if status == 1 {
                    let info:[String:Any] = dic["data"] as! Dictionary
                    let validTime = info["vipsurplusday"] ?? ""
                    DispatchQueue.main.async {
                        self.vipValidTimeLabel.text = "会员有效时间：\(validTime)"
                    }
                }
            }catch {
                
            }
        });
        task.resume();
    }
  
  @IBAction func checkIn() {
    checkInButton.isEnabled = false
    API.shared.requestAPI (
      APIURLStrings.checkIn,
      method: .put,
      header: API.shared.memeberHeader,
      successCallback: { json in
        HUD.flash(.labeledSuccess(title: "签到成功", subtitle: nil), delay: 1.0)
        self.checkInButton.isEnabled = false
        self.checkInButton.setTitle("今日已签到", for: .normal)
    }) { (message, code) in
      loggingPrint("CheckIn failed. \(message)")
      HUD.flash(.labeledError(title: "签到失败", subtitle: "请重试"), delay: 1.5)
      
      self.checkInButton.isEnabled = true
      self.checkInButton.setTitle("签到", for: .normal)
    }
  }
  
  @IBAction func displayCheckInInfo() {
    checkInStatusButton.isEnabled = false
    API.shared.requestAPI (
      APIURLStrings.totalCheckInTime,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        if let time = json["total_check_in_time"].int {
          let title = (time > 0 ? "您已签到\(time)次" : "您还没有签到记录")
          let alert = UIAlertController (
            title: title,
            message: nil,
            cancelTitle: "知道了",
            cancelHandler: nil
          )
          self.present(alert, animated: true)
        } else {
          HUD.flash(.labeledError(title: "签到信息读取失败", subtitle: "请重试"), delay: 1.5)
        }
        self.checkInStatusButton.isEnabled = true
    }) { (message, code) in
      loggingPrint("CheckIn failed. \(message)")
      HUD.flash(.labeledError(title: "签到信息读取失败", subtitle: "请重试"), delay: 1.5)
      
      self.checkInStatusButton.isEnabled = true
    }
  }
    //查看会员 加入会员 点击
    @objc func actionMemberButton(_ sender: UIButton) {
        self.tabBarController?.selectedIndex = 1
    }
    
    @objc func updateUserInfo(_ sender: NSNotification) {
        let info = sender.object as! Dictionary<UserDataChangeType ,Any>
        switch info.keys.first {
        case .HeadImage:
            avatarImageView.image = info.values.first as? UIImage
        case .NickName:
            nicknameLabel.text = info.values.first as? String
        default: break
            
        }
        
    }
  // MARK: - Public methods
  

}
